package com.imooc.miaosha.common;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.imooc.miaosha.validator.ValidatorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class ExceptionResolverConfig implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView(new FastJsonJsonView());
        if (e instanceof ValidatorException) {
            modelAndView.addObject("code", 0);
            modelAndView.addObject("msg", e.getMessage());
            modelAndView.addObject("data", null);

        } else {
            modelAndView.addObject("code", 0);
            modelAndView.addObject("msg", "error,系统敏感错误，请查看服务端日志！");
            modelAndView.addObject("data", null);
            e.printStackTrace();

        }
        return modelAndView;
    }
}
